package com.keepitsimple.core;

import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

public class Utils {
	/**
	 * 获取方法参数变量名
	 * @param clazz 	action。class
	 * @param methodName  方法名称
	 * @return	String[] 方法名数组
	 * @throws Exception
	 */
	public static String[] getParamNames(Class<?> clazz,String methodName) throws Exception{
		ClassPool pool=ClassPool.getDefault();
		/**
		 * 设置classPath 如果不设置会报错：
		 * javassist.NotFoundException
		 * The default ClassPool returned by a static method ClassPool.getDefault() searches the same path that the underlying 
		 * JVM (Java virtual machine) has. If a program is running on a web application server such as JBoss and Tomcat, 
		 * the ClassPoolobject may not be able to find user classes since such a web application server uses multiple class loaders 
		 * as well as the system class loader. In that case, an additional class path must be registered to the ClassPool. 
		 * 解决方法：
		 * 第一种解决方法：
		 * ClassPool pool = ClassPool.getDefault();
		 * ClassClassPath classPath = new ClassClassPath(this.getClass());
		 * pool.insertClassPath(classPath);
		 * 另一种解决方法：
		 * ClassPool pool = ClassPool.getDefault();
   		 *	pool.appendClassPath("E:\\xxx\\xxx\\target\\xxx_war\\WEB-INF\\lib\\xxx_jar-0.0.1-SNAPSHOT.jar");
		 */
		pool.insertClassPath(new ClassClassPath(Utils.class));
		CtClass ctClass = pool.get(clazz.getName());
		CtMethod ctMethod = ctClass.getDeclaredMethod(methodName);
		MethodInfo methodInfo = ctMethod.getMethodInfo();
		CodeAttribute codeAttr = methodInfo.getCodeAttribute();
		LocalVariableAttribute attr = (LocalVariableAttribute) codeAttr.getAttribute(LocalVariableAttribute.tag);
		if(attr==null){
			return null;
		}
		String[] paramsName = new String[ctMethod.getParameterTypes().length];
		int pos =Modifier.isStatic(ctMethod.getModifiers())?0:1;
		for (int i = 0; i < paramsName.length; i++)
		{
			paramsName[i] = attr.variableName(i+pos);
		}
		
		return paramsName;
	}
	public static String[] getActionParams(Class<?> clazz,String methodName) throws Exception {
		Object o =clazz.newInstance();
		
		String[] actionParams = new String[1];
		return null;
	}
}
